var mimeImage = {
	"application/xml" : "app/images/xml.png",
	"application/pdf" : "app/images/pdf.png",
	"application/rss+xml" : "app/images/rss.png"
}
var jarvis = new (function() {
	var queryEl;
	var lastSearch = null;

	this.init = function() {
		var that = this;
		queryEl = $("#search");

		//ajax
		var $loading = $('#loading').hide();
		$(document).ajaxStart(function() {
			$loading.show();
		}).ajaxStop(function() {
			$loading.hide();
		});

		// loading from bookmark
		var hash = window.location.hash;
		if (hash) {
			that.showToolbar();
			var q = hash.substring(1);
			that.updateResults(q);
			queryEl.val(q);
			lastSearch = q;
		}

		queryEl.focus();
		queryEl.keypress(function(e) {
			that.showToolbar();
			if (e.keyCode === 13) {
				var q = queryEl.val();
				if (q !== lastSearch) {
					lastSearch = q;
					window.location.hash = "#" + q;
					that.updateResults(q);
				}
			}
		});

		$(".corrupted").click(function() {
			that.showToolbar();
			that.showIncomplete();
		});
		$(".duplicates").click(function() {
			that.showToolbar();
			that.showDuplicates();
		});

	};

	this.showToolbar = function() {
		var that = this;
		if (!$("#toolbar").is(":visible")) {
			$("#home").addClass("hidden");
			$("#toolbar").removeClass("hidden");
			$("#results").removeClass("hidden");
			$(document.body).css("background", "#efefef");
			$("#toolbar .search-wrapper")
					.append(queryEl)
					.append(
							'<button id="search-btn" class="btn btn-info glyphicon glyphicon-search"></button>');

			queryEl.focus();
			$("#search-btn").click(function() {
				var q = queryEl.val();
				if (q !== lastSearch) {
					lastSearch = q;
					window.location.hash = "#" + q;
					that.updateResults(q);
				}
			});
		}
	};

	this.showDuplicates = function() {
		var that = this;
		$.ajax({
			type : "POST",
			url : "rest/duplicates"
		}).done(function(result) {
			if (typeof result !== "object") {
				result = JSON.parse(result);
			}
			var header = "Found " + result.length + " duplicates";
			$("#results .header .search-info").html(header);
			that.renderDuplicateResult(result);
		});

	};
	
	this.showIncomplete = function() {
		var that = this;
		$.ajax({
			type : "POST",
			url : "rest/incomplete"
		}).done(function(result) {
			if (typeof result !== "object") {
				result = JSON.parse(result);
			}
			var header = "Found " + result.hits.totalHits
					+ " results in " + result.took.secondsFrac
					+ " Seconds";
			$("#results .header .search-info").html(header);
			that.renderResult(result.hits.hits);
		});

	};

	this.updateResults = function(q) {
		var that = this;
		$.ajax({
			type : "POST",
			url : "rest/search",
			data : {
				query : q
			}
		}).done(
				function(result) {
					if (typeof result !== "object") {
						result = JSON.parse(result);
					}
					var header = "Found " + result.hits.totalHits
							+ " results in " + result.took.secondsFrac
							+ " Seconds";
					$("#results .header .search-info").html(header);
					that.renderResult(result.hits.hits);
				});
	};

	this.renderResult = function(results) {
		var html = '<ul class="list-group">';
		for (var i = 0; i < results.length; i++) {
			var source = results[i].source;
			var a = '<div class="media" content-type='
					+ source["Content-Type"]
					+ '>\
			  <a class="pull-left" href="#">\
			    <img class="media-object" src="'
					+ (mimeImage[source["Content-Type"]] || "http://placehold.it/50x50")
					+ '" alt="...">\
			  </a>\
			  <div class="media-body">\
			    <h4 class="media-heading">'
					+ (source.name || "No Title")
					+ '</h4>\
			  </div>\
			</div>';
			html += '<li class="list-group-item">' + a + '</li>';

		}
		html += '</ul>';
		$("#results-body").html(html);

	};

	this.renderDuplicateResult = function(results) {
		try {
			var html = '<ul class="list-group">';
			for (var i = 0; i < results.length; i++) {
				var dps = results[i].hits.hits;

				var related = '<div class="panel panel-warning">\
				  <div class="panel-heading">Duplicates</div>\
				  <div class="panel-body">';

				for (var j = 1; j < dps.length; j++) {
					related += '<span class="label label-default">'
							+ (dps[j]._source.name || "No Name") + '</span>';
				}
				related += '</div></div>';

				var source = dps[0]._source;
				var a = '<div class="media" content-type='
						+ source["Content-Type"]
						+ '>\
			  <a class="pull-left" href="#">\
			    <img class="media-object" src="'
						+ (mimeImage[source["Content-Type"]] || "http://placehold.it/50x50")
						+ '" alt="...">\
			  </a>\
			  <div class="media-body">\
			    <h4 class="media-heading">'
						+ (source.name || "No Title") + '</h4>\
			  </div>'
						+ related + '</div>';
				html += '<li class="list-group-item">' + a + '</li>';

			}
			html += '</ul>';
		} catch (e) {
			//console.log(e);
		}
		$("#results-body").html(html);

	};
});

$(function() {
	jarvis.init();
});